package com.fengye.algorithms.leecode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author fengye
 * @Date 2023/4/29 10:43
 **/
public class CombinationSumII40 {
    public static void main(String[] args) {
        new CombinationSumII40().combinationSum(new int[]{10,1,2,7,6,1,5}, 8).stream().forEach(System.out::println);
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(candidates == null || candidates.length == 0) {
            return res;
        }
        boolean[] visited = new boolean[candidates.length];
        // 排个序
        Arrays.sort(candidates);
        List<Integer> ans = new ArrayList<>();
        dfs(candidates, 0, candidates.length, visited, target, res, ans);
        return res;
    }

    public void dfs(int[] candidates, int begin, int len, boolean[] visited, int target, List<List<Integer>> res, List<Integer> ans) {
        //没有结果
        if(target < 0) {
            return;
        }
        // 符合结果
        if(target == 0) {
            res.add(new ArrayList<>(ans));
            return;
        }

        for(int i=begin;i<len;i++) {
            int n = candidates[i];
            // 排过序，不用计算了
            if(n > target) {
                return;
            }
            // 1、当前访问过了
            // 2、当前和前一个相等，并且前一个没有访问过，那么需要计算当前
            if(visited[i] || (i > 0 && candidates[i] == candidates[i-1] && !visited[i-1])){
                continue;
            }
            // 选择当前
            ans.add(n);
            visited[i] = true;
            // 继续递归
            dfs(candidates, i, len, visited,target - n, res, ans);
            // 回溯
            ans.remove(ans.size() - 1);
            visited[i] = false;
        }
    }
}
